<script setup lang="ts">

const captureScreenshot = async () => {
  try {
    // 获取屏幕或窗口的视频流
    const stream = await navigator.mediaDevices.getDisplayMedia({
      video: true
    })

    // 创建一个视频元素来加载视频流
    const video = document.createElement("video")
    video.srcObject = stream

    // 等待视频流加载完毕
    await new Promise((resolve) => (video.onloadedmetadata = resolve))

    // 设置视频宽高
    video.width = video.videoWidth
    video.height = video.videoHeight
    video.play()

    // 创建 canvas 并将视频当前帧绘制到 canvas
    const canvas = document.createElement("canvas")
    canvas.width = video.videoWidth
    canvas.height = video.videoHeight
    const ctx = canvas.getContext("2d")
    ctx.drawImage(video, 0, 0, canvas.width, canvas.height)

    // 停止视频流，释放资源
    stream.getTracks().forEach(track => track.stop())

    // 将 canvas 转换为图片并下载
    canvas.toBlob((blob) => {
      const link = document.createElement("a")
      link.href = URL.createObjectURL(blob)
      link.download = "screenshot.png"
      link.click()
      URL.revokeObjectURL(link.href) // 释放 URL 对象
    })
  } catch (err) {
    console.error("Error capturing screenshot:", err)
  }
}
</script>

<template>
  <button class="text-white bg-blue-600 ps-1 pe-1" @click="captureScreenshot">WebRTC Capture Screenshot</button>
</template>

<style scoped lang="scss">

</style>
